<?php
namespace Home\Controller;
use  Think\Controller;

class UserController extends Controller{

    public function login(){

        $this->display();
    }

    // 登陆
    // user  用户名
    // password 密码

    public function checklogin(){

        $user = I('user');
        $password = I('password');

        $res_user = M('user')->where("user = '".$user."'")->find();

        if($res_user){

            if($res_user['password'] == md5($password)){

                $dbtable = 'detail'.$res_user['level'];
                $res_detail = M($dbtable)->where("id = '".$res_user['detailid']."'")->find();

                // 更新登陆时间
                $arr_detail['loadtime'] = time();
                $res2 = M($dbtable)->where("id = '".$res_detail['id']."'")->save($arr_detail);

                unset($res_detail['id']);
                session('user',$res_detail);

                check_user_status($res_detail['userid']);

//                $data = genBody('1','登陆成功');
//                $this->ajaxReturn($data,'JSON');
                $this->redirect('Index/index','','1','登陆成功');
            }else{
                $this->redirect('User/login','','1','登陆失败');

            }
        }
    }

    public function register(){

        $this->display();

    }
    public function toregister(){

        $code = I('code');  // 根据邀请码来生成邀请者ID useredId
        $checkCode = I('checkcode');

        if($code){
            // TODO  每个人都可以生成一个属于自己的邀请码
            $where['code'] = $code;
            $usercode = M('user')->where($where)->find();

            if(!$usercode){

                $data = genBody('1','该邀请码不能使用，请更改');
                $this->ajaxReturn($data,'JSON');
            }

            $useredId = $usercode['id'];

            if($usercode['status'] == 2){

                $data = genBody('2','该邀请码暂时不能使用，请更改');
                $this->ajaxReturn($data,'JSON');
            }

        }else{

            $data = genBody('1','没有邀请码不允许注册');
            $this->ajaxReturn($data,'JSON');
        }

        // 检测验证码
        if(!empty($checkCode))
        {
            // 过期检测
            if(time() > $_SESSION['checkCode']['createTime'] + $_SESSION['checkCode']['expireTime'] * 60)
            {
                $data = genBody(3, '验证码已经过期');
                $this->ajaxReturn($data, 'JSONU');
            }
            if ( $checkCode != $_SESSION['checkCode']['code'])
            {
                // 验证码错误
                $data = genBody(3, '验证码错误');
                $this->ajaxReturn($data, 'JSONU');
            }
        }


        $user = D('user')->create();

        if(!$user){

            $this->ajaxReturn(D('user')->getError(),'JSON');
        }

        unset($user['code']);

        $res = M('user')->add($user);  // 如果验证通过，则注册为会员

        // 将详情添加进detail表
        $detail['phone'] = I('phone');
        $detail['regtime'] = time();
        $detail['loadtime'] = time();
        $detail['addres'] = I('addres');
        $detail['birthday'] = I('birthday');
        $detail['useredId'] = $useredId?$useredId:'';
        $detail['userId']  = $res;

        $detail2['phone'] = I('phone');
        $detail2['regtime'] = time();
        $detail2['loadtime'] = time();
        $detail2['addres'] = I('addres');
        $detail2['birthday'] = I('birthday');
        $detail2['useredid'] = $useredId?$useredId:'';
        $detail2['userid']  = $res;


        if($res){
            $detailrules = array(
                array('phone','/^1[3|4|5|8][0-9]\d{4,8}$/','手机号码错误','0','regex',1),
            );

            $detail1 = D('detail1');
            if(!$detail1->validate($detail)->create()){
                $data = $detail1->getError();
                $this->ajaxReturn($data,'JSON');
            }

            $res_detail = M('detail1')->add($detail);
            $user_where['id'] = $res;

            if($res_detail){

                session('user',$detail2);
                $res_user['detailId'] = $res_detail;

            }

            $pic1 = M('pic1');

            if(I('img')){

                $imginfo = getUploads();  // 上传图片
                // 保存当前数据对象
                $arr_pic['pic'] = '/'.Uploads.'/'.$imginfo['img']['savepath'].$imginfo['img']['savename'];
                $arr_pic['userId'] = $res;

                //插入图片表
                $res_pic  = $pic1->add($arr_pic);

                if($res_pic){

                    $res_user['picId'] = $res_pic;
                }

            }

            $result = M('user')->where($user_where)->save($res_user);


            if($result){
                $data = genBody('1','注册成功');
                $this->ajaxReturn($data,'JSON');
            }

        }

    }


    public function logout(){

        unset($_SESSION['user']);

        $this->redirect('User/login','','1','退出成功');
    }


    /**
     * 获取验证码
     * @phone 手机号
     * @return  0: 失败 1: 成功
     */
    public function getCheckCode(){
        $phone = I('phone');

        // 如果验证码没有过期，则从 session 中取出发送
        $msg_cfg = C('message');
        $expire_min = $msg_cfg['expire'];
        $now = time();
        if($now <= $_SESSION['checkCode']['createTime'] + $_SESSION['checkCode']['expireTime'] * 60 )
        {
            $checkCode = $_SESSION['checkCode']['code'];
        }else
        {
            // 生成验证码并放入 session, 设置过期时间
            $checkCode = $this->_genCheckCode();
            session('checkCode', array('code' => $checkCode, 'createTime' => $now, 'expireTime' => $expire_min));
        }

        // 给指定手机发送验证码
        $status = $this->_sendCheckCode($phone, $checkCode, $msg);
        if($status == 1)
        {
            if(isMsgOn()){
                $data = genBody(1);
            }else{
                $data = genBody(1, '测试阶段的短信功能关闭了(为节约短信资源)，验证码使用123代替');
            }

            $this->ajaxReturn($data, 'JSON');
        }
    }


    /**
     * 生成随机数(验证码)
     * @return int
     */
    private function _genCheckCode(){
        if(isMsgOn()){
            return mt_rand(1000, 9999);
        }else{
            // debug 测试阶段，短信发送开关为 关闭(false)的验证码为 123
            return 123;
        }
    }


    /**
     * @param $phone
     * @param $checkCode
     * @return 0: 失败 1: 成功
     */
    private function _sendCheckCode($phone, $checkCode, &$msg){
        // 调用短信平台发送验证码
        $msg_cfg = C('message');
        $expire = $msg_cfg['expire'];
        $replacement = array('CHECKCODE' => $checkCode, 'EXPIRE' => $expire);
        $content = strtr($msg_cfg['content_tpl'], $replacement);
        $param = array(
            'userid' => $msg_cfg['userid'],
            'account' => $msg_cfg['account'],
            'password' => $msg_cfg['password'],
            'content' =>$content,
            'mobile' =>$phone,
            'action' => 'send',
        );
        $msg_log = APP_PATH . 'message.log';
        // 短信发送开关开启
        if(isMsgOn()) {
            // 记录短信发送返回参数 && 请求短信接口的参数
            $xmlstring = request_post($msg_cfg['sendMsgUrl'], $param);
            if(APP_DEBUG) {
                @monitor_log($msg_log, $xmlstring, FILE_APPEND);
                @monitor_log($msg_log, $param, FILE_APPEND);
            }
            $xmlobj = simplexml_load_string($xmlstring);
            if($xmlobj->returnstatus == 'Success')
            {
                return 1;
            }else{
                $msg = $xmlobj->message;
                return 0;
            }
        }else{
            return 1;
        }
    }
}